library(geofacet)        #for plotting geographical regions 
library(ggalluvial)      #for alluvial plots
library(ggplot2)         #for data visualisation 
library(MetBrewer)       #for colour palettes
library(ragg)            #for saving data viz in png
library(showtext)        #for displaying fonts in data viz
library(stargazer)       #for model tables in latex
library(tidyverse)       #for data-wrangling

##data-wrangling----
BrSenSwitch <- read.csv("BrSenSwitch.csv", sep = ";") %>%
               mutate(fusao = ifelse(is.na(fusao), 0, fusao)) %>%
               mutate(fissao = ifelse(is.na(fissao), 0, fissao)) %>%
               mutate(partido_novo = ifelse(is.na(partido_novo), 0, partido_novo)) %>%
               mutate(home_inverted = 1-home) %>%
               filter(partido_novo != 1,
                      fissao != 1) %>%
               mutate(to_be_elected = case_when(legislatura == 48 ~ 1,
                                                legislatura == 49 ~ 2,
                                                legislatura == 50 ~ 1,
                                                legislatura == 51 ~ 2,
                                                legislatura == 52 ~ 1,
                                                legislatura == 53 ~ 2,
                                                legislatura == 54 ~ 1,
                                                legislatura == 55 ~ 2,
                                                legislatura == 56 ~ 1))

double_renovation <- BrSenSwitch %>% filter(to_be_elected == 2) 
single_renovation <- BrSenSwitch %>% filter(to_be_elected == 1)

##fonts----
#These fonts can be obtained here: https://fonts.google.com/specimen/Barlow+Semi+Condensed
font_add(family = "regular", "Barlow Semi Condensed-Regular.ttf")
font_add(family = "bold", "BarlowSemiCondensed-SemiBold.ttf")
showtext_auto() 

##Figure1----
br <- BrSenSwitch %>%
      mutate(fusao = ifelse(is.na(fusao), 0, fusao)) %>%
      mutate(partido_novo = ifelse(is.na(partido_novo), 0, partido_novo)) %>%
      filter(fusao != 1,
             partido_novo != 1) %>%
      select(senador, partido_inicial, partido_final, mes, ano, home, y) %>%
      group_by(senador, mes, partido_final, ano) %>%
      filter(home != y) %>%
      summarise(n = n()) %>%
      filter(partido_final != "PPR") %>%
      ungroup() %>%
      group_by(ano) %>%
      summarise(n = n())

br2 <- tribble(
  ~ano, ~n, 
  1998, 0,
  2008, NA,
  2009, NA,
  2010, NA,
  2011, NA,
  2012, NA,
  2013, NA,
  2014, NA,
)

a1990 <- data.frame(xmin1=1990, xmax1=1990.5, ymin1= 0, ymax1=23)
a1994 <- data.frame(xmin1=1993.5, xmax1=1994.5, ymin1= 0, ymax1=23)
a1998 <- data.frame(xmin1=1997.5, xmax1=1998.5, ymin1= 0, ymax1=23)
a2002 <- data.frame(xmin1=2001.5, xmax1=2002.5, ymin1= 0, ymax1=23)
a2006 <- data.frame(xmin1=2005.5, xmax1=2006.5, ymin1= 0, ymax1=23)
a2010 <- data.frame(xmin1=2009.5, xmax1=2010.5, ymin1= 0, ymax1=23)
a2014 <- data.frame(xmin1=2013.5, xmax1=2014.5, ymin1= 0, ymax1=23)
a2018 <- data.frame(xmin1=2017.5, xmax1=2018.5,  ymin1= 0, ymax1=23)
a2022 <- data.frame(xmin1=2021.5, xmax1=2022,  ymin1= 0, ymax1=23)


br3 <- br %>% rbind(br2)

br3 %>% ggplot(aes(ano, n, fill = "black")) +
  geom_line(linewidth = 1.2) +
  geom_rect(data = a1990, aes(xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1),
            fill = "grey",
            alpha = 0.4,
            inherit.aes = FALSE) +
  geom_rect(data = a1994, aes(xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1),
            fill = "grey",
            alpha = 0.4,
            inherit.aes = FALSE) +
  geom_rect(data = a1998, aes(xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1),
            fill = "grey",
            alpha = 0.4,
            inherit.aes = FALSE) +
  geom_rect(data = a2002, aes(xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1),
            fill = "grey",
            alpha = 0.4,
            inherit.aes = FALSE) +
  geom_rect(data = a2006, aes(xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1),
            fill = "grey",
            alpha = 0.4,
            inherit.aes = FALSE) +
  geom_rect(data = a2010, aes(xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1),
            fill = "grey",
            alpha = 0.4,
            inherit.aes = FALSE) +
  geom_rect(data = a2014, aes(xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1),
            fill = "grey",
            alpha = 0.4,
            inherit.aes = FALSE) +
  geom_rect(data = a2018, aes(xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1),
            fill = "grey",
            alpha = 0.4,
            inherit.aes = FALSE) +
  geom_rect(data = a2022, aes(xmin = xmin1, xmax = xmax1, ymin = ymin1, ymax = ymax1),
            fill = "grey",
            alpha = 0.4,
            inherit.aes = FALSE) +
  scale_x_continuous(limits = c(1990, 2022.3),
                     breaks = seq(1990, 2022, by = 2)) +
  scale_y_continuous(limits = c(-0.2, 23),
                     breaks = seq(0, 22, by = 2)) +
  coord_cartesian(expand=FALSE) +
  xlab("") + ylab("Frequence of Party Switching") +
  theme(
    #Title, Subtitle, Caption
    plot.title = element_text(family = "bold", hjust = 0.5, vjust = 0.5, size = 50, color = "white"),
    plot.title.position = "plot",
    plot.subtitle = element_text(family="bold", size = 25, hjust = 0.5, color = "white"),
    plot.caption = element_text(family="bold", size = 30, color = "white", hjust = 1),
    plot.caption.position = "plot",
    #Panel and Background
    panel.border = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_rect(fill = "white"),
    plot.background = element_rect(fill = "white", linetype = 'blank'),
    #Axes
    axis.title = element_text(size = 50, family = "regular", color = "black"),
    axis.text.y = element_text(size = 40, family = "regular", color = "black"),
    axis.text.x = element_text(size = 34, family = "regular", color = "black"),
    axis.ticks = element_blank(),
    axis.line = element_blank(),
    #Plus
    text = element_text(family = "regular", size = 45),
    legend.position = "none") -> fi

ggsave("Figure1.png",
       plot=fi,
       device = agg_png(width = 8, height = 6, units = "in", res = 300))

##Figure2----
pairs_ <- BrSenSwitch %>%
          filter(fusao != 1) %>%
          filter(partido_novo != 1) %>%
          filter(partido_inicial != "S/PART",
                 partido_final != "S/PART") %>%
          mutate(partido_inicial = case_when(partido_inicial == "MDB" ~ "PMDB",
                                             T ~ partido_inicial)) %>%
          mutate(partido_final = case_when(partido_final == "MDB" ~ "PMDB",
                                           T ~ partido_final)) %>%                 
          select(senador, mes, ano, partido_inicial, partido_final, home, y) %>%
          group_by(senador, mes, ano, partido_inicial, partido_final) %>%
          filter(home != y) %>%
          summarise(n = n()) %>%
          ungroup() %>%
          group_by(partido_inicial, partido_final) %>%
          summarise(n = n()) %>%
          arrange(desc(n)) %>%
          filter(n >= 3) %>%
          ungroup() %>%
          filter(partido_final != "PPR") %>%
          group_by(partido_final) %>%
          mutate(n_final = sum(n)) %>%
          ungroup() %>%
          filter(n_final >= 11)

my_palette <- met.brewer("Pissaro", 2)

pairs_ %>% ggplot(aes(axis1 = partido_inicial, 
                      axis2 = partido_final,
                      y = n)) +
  geom_alluvium(aes(fill = partido_final)) +
  geom_stratum(aes(fill = partido_final)) +
  scale_fill_manual(values=my_palette) +
  scale_x_discrete(limits = c("Left", "Joined"),expand = c(.2, .05)) +
  geom_text(stat = "stratum", aes(label = after_stat(stratum)), size = 20, family = "regular") +
  geom_text(stat = "stratum", aes(label = n), vjust = 2, size = 15, family = "regular") +
  geom_text(aes(x = 2, y = 4.5, label = 11), size = 15, family = "regular") +
  geom_text(aes(x = 2, y = 17.5, label = 15), size = 15, family = "regular") +
  xlab("Party Switching") + ylab("Frequence") +
  coord_cartesian(expand=FALSE) +
  theme(
    #Title, Subtitle, Caption
    plot.title = element_text(family = "bold", hjust = 0.5, vjust = 0.5, size = 50, color = "white"),
    plot.title.position = "plot",
    plot.subtitle = element_text(family="bold", size = 25, hjust = 0.5, color = "white"),
    plot.caption = element_text(family="bold", size = 30, color = "white", hjust = 1),
    plot.caption.position = "plot",
    #Panel and Background
    panel.border = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_rect(fill = "white"),
    plot.background = element_rect(fill = "white", linetype = 'blank'),
    #Axes
    axis.title = element_text(size = 50, family = "regular", color = "black"),
    axis.text.y = element_text(size = 30, family = "regular", color = "black"),
    axis.text.x = element_text(size = 35, family = "regular", color = "black"),
    axis.ticks = element_blank(),
    axis.line = element_blank(),
    #Plus
    text = element_text(family = "regular", size = 45),
    legend.position = "none") -> ps

ggsave("Figure2.png",
       plot=ps,
       device = agg_png(width = 8, height = 6, units = "in", res = 300))
